import store from '@/store/index'
import Vue from 'vue'
import VueRouter from 'vue-router'
import nprogress from 'nprogress'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/',
    component: () => import('@/views/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      { path: '/dashboard', component: () => import('@/views/dashboard/index.vue') },
      { path: '/statistics', component: () => import('@/views/statistics/index.vue') },
      { path: '/order', component: () => import('@/views/order/index.vue') },
      { path: '/setmeal', component: () => import('@/views/setmeal/index.vue') },
      { path: '/setmeal/add', component: () => import('@/views/setmeal/addSetmeal.vue') },
      { path: '/dish', component: () => import('@/views/dish/index.vue') },
      { path: '/dish/add', component: () => import('@/views/dish/addDish.vue') },
      { path: '/category', component: () => import('@/views/category/index.vue') },
      { path: '/employee', component: () => import('@/views/employee/index.vue') },
      { path: '/employee/add', component: () => import('@/views/employee/addEmployee.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 进度条
nprogress.configure({ showSpinner: false })

const authUrls = ['/layout', '/dashboard', '/statistics', '/order', '/setmeal', '/dish']

router.beforeEach((to, from, next) => {
  nprogress.start()
  if (!authUrls.includes(to.path)) {
    // 不是权限页面
    next()
    return
  }

  // 是权限页面，检查是否有token
  const token = store.state.user.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

router.afterEach((to, from, next) => {
  nprogress.done()
})

export default router
